let app = getApp();
let API_URL = app.globalData.API_URL;
import { getHouseDetail } from "../../../../request/api.js";
import dayjs from "../../../../common/js/dayjs.js"

Page({
    /**
     * 页面的初始数据
     */
    data: {
        lang: null,
        postId: null,
        current: '',
        isLike: false,
        isIphone: false,
        previewImageList: [],
        detailed: {},
        detailedBoxList: [
            { id: 1, name: 'price', value_ug: 'price_ug', value_zh: 'price_zh', unit2:'yuan' },
            { id: 2, name: 'area', value_ug: 'area', value_zh: 'area', unit:"houseUnit", unit2:'houseUnit' },
            { id: 3, name: 'unitType',value_ug: 'unitType_ug', value_zh: 'unitType_zh' },
            { id: 4, name: 'buildingTime',value_ug: 'buildTime', value_zh: 'buildTime' },
            { id: 5, name: 'floor', value_ug: 'floor', value_zh: 'floor' },
            { id: 6, name: 'decoration',value_ug: 'processing_ug', value_zh: 'processing_zh' }
        ],
        phoneNumber: '',
        weChat: ''
    },

    /**
     * My Function
     */
    // 获取内容
     getPost() {
        let postId = this.data.postId
        let data = { postId }
        getHouseDetail(res => {
            if(res.statusCode == 200) {
                let time = res.data
                if (time.favorite != null) {
                    this.setData({ isLike: true })
                }
                time.releaseTime = dayjs(time.releaseTime).format("YYYY-MM-DD")
                this.setData({ detailed: res.data })
                this.getPhoneNumber();
            }
        }, data);
     },

    // 收藏
    onLike() {
        let user_id = wx.getStorageSync('uid')
        if (!user_id) {
            app.login()
            return
        }
        let data = { target_id: parseInt(this.data.postId, 10), type: 3 }
        
        if(this.data.isLike) {
            let data = { postId: this.data.detailed.favorite.id }
            wx.request({
                url: `${API_URL}/favoritesDestroy`,
                data: data,
                header: app.header(),
                method: 'post',
                success: res=> {
                    if(res.statusCode == 200) {
                        this.setData({ isLike: false })
                        wx.showToast({
                            title: 'ok',
                            duration: 2000
                        })
                    }
                }
            })
        } else {
            wx.request({
                url: `${API_URL}/favorites`,
                data: data,
                header: app.header(),
                method: 'post',
                success: res=> {
                    if(res.statusCode == 200) {
                        let favorite = {
                            id : res.data.insertId
                        }
                        let detailed = this.data.detailed
                        detailed.favorite = favorite
                        this.setData({ isLike: true, detailed: detailed })
                        wx.showToast({
                            title: 'ok',
                            duration: 2000
                        })
                    }
                }
            })
        }
    },

    // 打电话联系
    onContact() {
        app.login()
        wx.makePhoneCall({
            phoneNumber: this.data.detailed.phoneNum,
            fail: cancel => {
                console.log("cancel: ", cancel);
            }
        })
    },

    // 预览图
    preview(event) {
        let src = event.currentTarget.dataset.src.fullUrl;
        let previewImage = this.data.detailed.images;
        let urls = []
        for(let item of previewImage){
            urls.push(item.fullUrl)
        }
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: urls // 需要预览的图片http链接列表
        })
    },

    // 支付
    payment() {
        let bodyCon = '[房屋]' + this.data.detailed.name_zh + '的联系方式'
        let commodity_id =this.data.detailed.id
        let commodity_type =3
        let data = { bodyCon, commodity_id, commodity_type }
        let that = this

        // 没登录的先登录再付款
        let promise = new Promise(function(resolve, rej) {
            app.login(res => {
                resolve(res)
            })
        })

        promise.then(
            resolve => {
                wx.request({
                    url: `${API_URL}/payments`,
                    data: data,
                    header: app.header(),
                    method: 'post',
                    success: res=> {
                        // this.callPayment(res.data.timeStamp, res.data.nonceStr, res.data.package, res.data.paySign)
                        wx.requestPayment({
                            nonceStr: res.data.nonceStr,
                            package: res.data.package,
                            paySign: res.data.paySign,
                            signType: "MD5",
                            timeStamp: res.data.timeStamp,
                            success(res) {
                                that.getPost();
                             },
                            fail(res) {
                                console.log("用户取消支付: ", res);
                            }
                        })
                    }
                })
            }
        )
    },

    // 调用支付
    callPayment(timeStamp, nonce_str, pkg, sign) {
        wx.requestPayment({
            timeStamp: timeStamp,
            nonceStr: nonce_str,
            package: pkg,
            signType: 'MD5',
            paySign: sign,
            success(res) {
                console.log("res:", res)
             },
            fail(res) {
                console.log("err: ", res);
            }
        })
    },

    // 支付成功后再次获取手机号
    getPhoneNumber() {
        // 判断是否苹果产品
        let phone = this.data.detailed.phoneNum;
        let weChat = this.data.detailed.weChat;
        let paymentStatus = this.data.detailed.paymentStatus
        if(this.data.isIphone) {
            this.setData({ phoneNumber: this.data.detailed.phoneNum });
            this.setData({ weChat: this.data.detailed.weChat });
            return;
        }
        if (paymentStatus == 1) {
            this.setData({ phoneNumber: this.data.detailed.phoneNum })
            this.setData({ weChat: this.data.detailed.weChat })
        } else {
            var str2 = phone.substring(0, 3) + '******' + phone.substring(9);
            var str3 = weChat.substring(0, 3) + '******'
            this.setData({ phoneNumber: str2, weChat: str3 })
        }
    },

    /**
     * App Function
     */

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({ lang: app.globalData.lang, postId: options.itemId, navTitle: "housingInfo", navigation: true, isIphone: app.globalData.isIphone })
        this.getPost()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    /**
     * 朋友圈分享
     */
    onShareTimeline: function () {
        return {
            imageUrl: `${this.data.detailed.images[0].fullUrl}`,
            title: `${ this.data.lang.dir == "rtl" ? this.data.detailed.name_ug : this.data.detailed.name_zh }`,
            path: '/pages/home/house/houseDetaild/houseDetaild?postId=' + this.data.postId
        }
    }
})